package com.xyzh05.dao.hibernate;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.xyzh05.dao.RoleDao;
import com.xyzh05.model.Role;


/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve Role objects.
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> 
 */
@Repository
public class RoleDaoHibernate extends GenericDaoHibernate<Role, Long> implements RoleDao {

    /**
     * Constructor to create a Generics-based version using Role as the entity
     */
    public RoleDaoHibernate() {
        super(Role.class);
    }

    /**
     * {@inheritDoc}
     */
    public Role getRoleByName(String rolename) {
        List roles = getHibernateTemplate().find("from Role where name=?", rolename);
        if (roles.isEmpty()) {
            return null;
        } else {
            return (Role) roles.get(0);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void removeRole(String rolename) {
        Object role = getRoleByName(rolename);
        getHibernateTemplate().delete(role);
    }
    
    public Short existUserBind(Long userId){
    	String sql = "select status from role where update_user=" + userId;
    	return (Short) getSession().createSQLQuery(sql).uniqueResult();
    }
    
    @SuppressWarnings("unchecked")
	public List<Role> getUserBindList(List<Long> deptIds, List<Long> userIds, Short roleType, Short status){
    	String sql = "select * from role where 1=1";
    	if(deptIds != null && !"".equals(deptIds)){
    		sql += " and dept_id in(" + deptIds.toString().replaceAll("[\\[\\]]", "") + ")";
    	}
    	if(userIds != null && !"".equals(userIds)){
			sql += " and update_user in(" + userIds.toString().replaceAll("[\\[\\]]", "") + ")";
    	}
    	if(roleType != null && !"".equals(roleType)){
    		sql += " and role_type_id=" + roleType;
    	}
    	if(status != null && !"".equals(status)){
    		sql += " and status=" + status;
    	}
    	return getSession().createSQLQuery(sql).addEntity(Role.class).list();
    }
}
